package durak;

import java.util.ArrayList;

import FrenchCards.FrenchCardRank;
import FrenchCards.FrenchCardSuit;

import cards.Deck;
import cards.DeckShuffler;

public class Game {

	ArrayList<Player> mPlayers;
	Player mAttacker;
	Player mDefender;
	DurakTable mTable;
	DurakDeck mDeck;
	int initHandSize = 6;

	DurakCard mTrumpSuit;

	DeckShuffler deckShuffler = new DurakDefaultDeckShuffler();


	void initDraw() {
		for (int i = 0; i < initHandSize; ++i)
			for (Player player : mPlayers)
				player.drawCard(mDeck);

		mTrumpSuit = mDeck.getTopCard();
		mDeck.putToBottom(mTrumpSuit);
		
		System.out.println("TrumpSuit : "+ mTrumpSuit.getInfo().suit);
	}
	
	void firstPlayerDetection()
	{

		FrenchCardRank smallestTrumpRank = null ;
		FrenchCardSuit trumpSuit = mTrumpSuit.getInfo().suit;
		
		for (Player player : mPlayers)
			for(DurakCard card : player.mHand)
			{
				if (card.getInfo().suit.equals(trumpSuit) )
					if (smallestTrumpRank == null || smallestTrumpRank.compareTo( card.getInfo().rank ) > 0 )
					{
						smallestTrumpRank = card.getInfo().rank;
						mAttacker = player;
						
						if(mPlayers.indexOf(mAttacker) == mPlayers.size()-1)
							mDefender = mPlayers.get(0);
						else
							mDefender = mPlayers.get(mPlayers.indexOf(mAttacker) + 1);
						
						System.out.println("Attack player["+mPlayers.indexOf(mAttacker)+"]. Defend player["+mPlayers.indexOf(mDefender)+"]");
					}
			}
	}
	
	void turn()
	{
		
		DurakCard attackCard = mAttacker.onAttack();
		mTable.putAttackCard(attackCard);
		
		DurakCard[] result = mDefender.onDefend();
		mTable.beatCard(result[0], result[1]);
	}

	public void init() {
		deckShuffler.shuffle(mDeck);
		initDraw();
		firstPlayerDetection();
		turn();
	}

	public Game() {
		mPlayers = new ArrayList<Player>();
		mDeck = new DurakDeckBuilder().build();
		mTable = new DurakTable();
		mTable.setDeck(mDeck);
	}
	
	public void addPlayer(Player aPlayer)
	{
		mPlayers.add(aPlayer);
		aPlayer.sitDown(mTable);
	}

}
